package com.example.music.Controller;

import com.example.music.model.Music;
import com.example.music.model.User;
import com.example.music.service.LoveMusicService;
import com.example.music.service.MusicService;
import com.example.music.tool.Constant;
import com.example.music.tool.ResponMessage;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/music")
public class MusicController {
   @Autowired
   MusicService musicService;
   @Autowired
   LoveMusicService loveMusicService;
   @Value("${music.local.path}")
   public String Save_Path;
   //上传音乐
   @RequestMapping("/opload")
      public ResponMessage<Boolean> insertMusic(@RequestParam String
                                                              singer, @RequestParam("filename") MultipartFile file, HttpServletRequest req,
                                                      HttpServletResponse resp,HttpSession httpSession) throws IOException {
         if(httpSession == null ||
                 httpSession.getAttribute(Constant.USERINFO_SESSION_KEY) == null) {
            System.out.println("没有登录！");
            return new ResponMessage<>(-1,"没有登录！",false);
         }
         String filenameAndType = file.getOriginalFilename();//xxx.mp3
         System.out.println("filenameAndType--- >>>>>>>>>>>>>>>>>"+filenameAndType);
         String path = Save_Path +"/"+filenameAndType;
         File dest = new File( path);
         System.out.println("dest:=>" + dest.getPath());
         if(!dest.exists()) {
            dest.mkdirs();
         }
         try {
            System.out.println(dest);
            file.transferTo(dest);//上传⽂件到⽬标

         } catch (IOException e) {
            e.printStackTrace();
            return new ResponMessage<>(-1,"上传失败！",false);
         }

//      int insert(String title, String singer, String time, String url,int
//      userid);
      String title=filenameAndType.substring(0,filenameAndType.lastIndexOf("."));
         String time=new SimpleDateFormat("yyyy-MM-dd").format(new Date());
         String url="/music/get?path="+title;
      User user= (User) httpSession.getAttribute(Constant.USERINFO_SESSION_KEY);
      int userid=user.getId();
     int ret=musicService.insert(title,singer,time,url,userid);
      if(ret == 1){
         //resp.sendRedirect("/list.html"); 前端实现好后需要更改，跳转⻚⾯
      }else{
         //System.out.println("上传失败！");
         dest.delete();
         return new ResponMessage<>(-1,"数据库上传失败,删除上传的⾳乐！",false);
      }
      return new ResponMessage<>(0,"上传成功！",true);
   }
   //
   @RequestMapping("/get")
   public ResponseEntity<byte[]> get(String path){
      try {
         byte[] bytes = Files.readAllBytes(new File(Save_Path+File.separator+path).toPath());
         return ResponseEntity.ok(bytes);
      } catch (IOException e) {
         e.printStackTrace();
      }
      return null;
   }
   //删除音乐存在的痕迹
@RequestMapping("/delete")
   public ResponMessage<Boolean> delete(@RequestParam String id){
      int iid=Integer.parseInt(id);
   Music music=musicService.findMusicById(iid);
   if(music==null){
      return new  ResponMessage<>(-1,"数据库中没有这个数据",false);
   }else {
      int de=musicService.deleteMusicById(iid);
      if(de!=1){
         return new  ResponMessage<>(-1,"数据库数据删除失败",false);
      }else {
         File file = new File(Save_Path + "/" + music.getTitle() + ".mp3");

         if (file.delete()) {
            loveMusicService.deleteLoveMusicById(iid);
            return new ResponMessage<>(1, "服务器和数据库数据删除成功", true);
         } else {
            return new ResponMessage<>(-1, "服务器数据删除失败", false);
         }
      }
   }

}
//批量删除
   @RequestMapping("/deleteSel")
   public ResponMessage<Boolean> deleteSelMusic(@RequestParam("selectedIds")
                                                List<Integer> id) {
      System.out.println("id[]"+id);
      int sum=0;
      for(int i=0;i<id.size();i++){
         int iid=id.get(i);
         Music music=musicService.findMusicById(iid);
         if(music==null){
            return new  ResponMessage<>(-1,"数据库中没有这个数据",false);
         }else {
            int de=musicService.deleteMusicById(iid);
            if(de<0){
               return new  ResponMessage<>(-1,"数据库数据删除失败",false);
            }else {
               File file = new File(Save_Path + "/" + music.getTitle() + ".mp3");

               if (file.delete()) {
                  loveMusicService.deleteLoveMusicById(iid);
                  sum++;
               } else {
                  return new ResponMessage<>(-1, "服务器数据删除失败", false);
               }
            }
         }
      }
      if(sum!=id.size()){
         System.out.println("服务器和数据库数据删除失败");
      }

         return new ResponMessage<>(1, "服务器和数据库数据删除成功", true);

   }
   //查询音乐
   @RequestMapping("/findmusic")
   public ResponMessage<List<Music>> findmusic(@RequestParam(required = false) String title,HttpSession httpSession){
      if(httpSession == null ||
              httpSession.getAttribute(Constant.USERINFO_SESSION_KEY) == null) {
         System.out.println("没有登录！");
         return new ResponMessage<>(-1,"没有登录！",null);
      }
      List<Music> musicList=new ArrayList<>();
      if(title==null){
         musicList=musicService.findAll();
      }else {
         musicList.add(musicService.findBylike(title));
      }
      return new ResponMessage<>(1,"查询成功", musicList);

   }

   }



